import {IUser} from "@/types/store/user";
import {Session} from "@/utils/storage";
import {IUserInfo} from "@/api/types/user";
import {ActionContext} from "vuex";
import {ILoginResponse} from "@/api/types/common";

const USER_INFO = 'userInfo'
const TOKEN = 'token'
const EXPIRES_IN = 'expiresIn'

const state: IUser = {
  user: Session.get<IUserInfo>(USER_INFO),
  token: Session.get<string>(TOKEN),
  expiresIn: Session.get<number>(EXPIRES_IN)
}

const mutations = {
  setUser(state: IUser, user: IUserInfo) {
    state.user = user
    Session.set(USER_INFO, user)
  },
  setToken(state: IUser, token: string) {
    state.token = token
    Session.set(TOKEN, token)
  }
}

const actions = {
  login(context: ActionContext<IUser, any>, param: ILoginResponse) {
    context.commit('setUser', param.userInfo)
    context.commit('setToken', param.token)
    // 超時時間
    context.state.expiresIn = param.expiresIn
    Session.set(EXPIRES_IN, param.expiresIn+'')
  }
}

const userState = {
  namespaced: true,
  state,
  mutations,
  actions
}

export default userState
